import { useSelector } from "react-redux";
import PropTypes from "prop-types";

const ALL_PERMISSION = "*:*:*";

const hasPermission = (auth, permissions) => {
  return permissions.includes(auth) || permissions.includes(ALL_PERMISSION);
};

/**
 * 权限按钮
 *
 * @param {String} auth 权限标识
 * @returns
 */
const AuthButtonComponent = ({ auth, children }) => {
  const userStore = useSelector((state) => state.user.value);

  const isAdmin = userStore?.user?.admin || false;
  const { permissions } = userStore;

  if (permissions) {
    const isHasPerm = hasPermission(auth, permissions);
    if (!auth || isAdmin === true || isHasPerm) {
      return children;
    }
  }

  return <></>;
};

// 对 auth 进行类型检查
AuthButtonComponent.propTypes = {
  auth: PropTypes.string.isRequired, // 假设 auth 应该是一个字符串
  children: PropTypes.node.isRequired,
};

export default AuthButtonComponent;
